//
//  ViewController.m
//  myPhonebook
//
//  Created by liuchengming on 16/4/27.
//  Copyright © 2016年 liuchengming. All rights reserved.
//

#import "ViewController.h"
#include "Phonedata.h"

@interface ViewController ()
{
    NSArray * data;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.title = @"我的通讯录";
    UITableView * tableview = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    tableview.dataSource = self ;
    
    [self.view insertSubview:tableview aboveSubview:tableview];
    
    NSBundle * bunle = [NSBundle mainBundle];
    
    NSURL * url = [bunle URLForResource:@"00001" withExtension:@"vcf"];
    NSString * text = [[NSString alloc]initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
    //NSLog(@"%@",text);
    
    NSArray * lines = [text componentsSeparatedByString:@"\n"];
    NSMutableArray * d =[NSMutableArray new];
    Phonedata * item ;
    for (NSString * line in lines)
    {
        //NSArray * item = lines;
        if ([line hasPrefix:@"BEGIN"])
        {
            item = [Phonedata new];
        } else if ([line hasPrefix:@"END"])
        {
            [d addObject:item];
        }else if([line hasPrefix:@"TEL"])
        {
            NSArray * components = [line componentsSeparatedByString:@":"];
            NSString * tel = components[1];
            //NSLog(@"%@",tel);
            item.tel = tel;
            
        }else if([line hasPrefix:@"FN:"])
        {
            NSArray *upperComponents = [line componentsSeparatedByString:@":"];
            NSString *name = upperComponents[1];
            name = [name stringByReplacingOccurrencesOfString:@"=" withString:@"%"];
            name = [name stringByRemovingPercentEncoding];
            //NSLog(@"FN:%@",name);
            item.name = name;
            
            [d addObject:item];
            
        }
    }
    data = d;
    
    
    
    
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return data.count;
}
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell * cell =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
    Phonedata * p = data[indexPath.row];
    cell.textLabel.text = p.name;
    cell.detailTextLabel.text = p.tel;
    return cell;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
